# node_b.py
import random
import grpc
from concurrent import futures
import time
import quotes_pb2
import quotes_pb2_grpc

B_QUOTES = [
    "当星星变成星空，梦想也就近在咫尺了。",
    "别总因为迁就别人,委屈了自己,这个世界上,没几个人值得你总弯腰",
]


class QuoteServiceB(quotes_pb2_grpc.QuoteServiceServicer):
    def GetQuote(self, request, context):
        zh = random.choice(B_QUOTES)
        return quotes_pb2.QuoteResponse(zh=zh, en="", pic="")


def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=5))
    quotes_pb2_grpc.add_QuoteServiceServicer_to_server(QuoteServiceB(), server)
    server.add_insecure_port("[::]:50052")
    server.start()
    print("B 节点已启动，监听 50052")
    return server


def call_a():
    with grpc.insecure_channel("localhost:50051") as channel:
        stub = quotes_pb2_grpc.QuoteServiceStub(channel)
        response = stub.GetQuote(quotes_pb2.Empty())
        print(
            f"B 节点作为客户端请求 A ，获得响应：\n{response.zh}\n{response.en}\n{response.pic}"
        )


if __name__ == "__main__":
    server = serve()
    try:
        time.sleep(1)  # 等待 A 启动
        call_a()
        server.wait_for_termination()
    except KeyboardInterrupt:
        server.stop(0)
